package com.aaa.shuke2024.controller;

import com.aaa.shuke2024.entity.MyReturn;
import com.aaa.shuke2024.entity.User;
import com.aaa.shuke2024.service.UserService;
import com.aaa.shuke2024.utils.MyTools;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 用户信息表(User)表控制层
 *
 * @author teacherChen
 * @since 2024-12-02 16:09:10
 */
@RestController
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    /**
     * 分页查询
     *
     * @param user 筛选条件
     * @param page      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<User>> queryByPage(User user,int page,int limit) {
        PageRequest pageRequest = PageRequest.of(page-1, limit);
        return ResponseEntity.ok(this.userService.queryByPage(user, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<User> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.userService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param user 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<User> add(User user) {
        return ResponseEntity.ok(this.userService.insert(user));
    }

    /**
     * 编辑数据
     *
     * @param user 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<User> edit(User user) {
        return ResponseEntity.ok(this.userService.update(user));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.userService.deleteById(id));
    }

    @RequestMapping("/login")
    @ResponseBody
    public MyReturn login(User user){
        MyReturn myReturn = new MyReturn();
        //用户是否存在
        User userByUsername = userService.findUserByUsername(user.getUsername());
        if(null !=userByUsername){
            //密码校验
           // User userByUsernameAndPassword = userService.findUserByUsernameAndPassword(user.getUsername(), user.getPassword());
            boolean checkPassword = MyTools.checkPassword(user.getPassword(), userByUsername.getSalt(), userByUsername.getPassword());
            if(checkPassword){
                //认证成功，允许登录
                myReturn.setCode(0);
                myReturn.setMsg("认证成功");
                myReturn.setData(userByUsername);
            }else{
                //密码不正确
                myReturn.setCode(1);
                myReturn.setMsg("密码不正确");
            }
        }else{
            //用户不存在
            myReturn.setCode(1);
            myReturn.setMsg("用户名不存在");
        }

        return  myReturn;
    }
}

